#include "main.h"

static size_t DownloadCallBack(void *contents,size_t size,size_t nmemb,FILE *stream);

bool Download(const char *URL,const char *FileName){
	FILE *file = fopen(FileName,"wb+");
	curl_global_init(CURL_GLOBAL_DEFAULT); 
	CURLcode success;
	double File_size = 0;
	double speed = 0;
	CURL *easy_handle = curl_easy_init();
	curl_easy_setopt(easy_handle,CURLOPT_URL,url_escape(URL));
	curl_easy_setopt(easy_handle,CURLOPT_WRITEFUNCTION,DownloadCallBack);
	//curl_easy_setopt(easy_handle,CURLOPT_FOLLOWLOCATION,1);
	curl_easy_setopt(easy_handle,CURLOPT_SSL_VERIFYPEER,false);
	curl_easy_setopt(easy_handle,CURLOPT_SSL_VERIFYHOST,false);
	curl_easy_setopt(easy_handle,CURLOPT_WRITEDATA,file);
	curl_easy_setopt(easy_handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.368    3.75 Safari/537.36");
	success = curl_easy_perform(easy_handle);
	if(success != CURLE_OK){
		std::cout << FAILED << "下载错误" << std::endl;
		return false;
	}
	if(CURLE_OK == curl_easy_getinfo(easy_handle,CURLINFO_SIZE_DOWNLOAD,&File_size)){
					std::cout << "文件大小为:" << File_size/1024 << "KB" << std::endl; 
	}
	else
					std::cout << "未知大小" << std::endl;

	if(CURLE_OK == curl_easy_getinfo(easy_handle,CURLINFO_SPEED_DOWNLOAD,&speed))
					std::cout << "下载速度为:" << speed/1024 << "KB/S" << std::endl;
	else
					std::cout << "未知下载速度" << std::endl;

	std::cout << SUCCESS << "下载" << URL << " 成功." << std::endl;
	curl_easy_cleanup(easy_handle);
	curl_global_cleanup();
	fclose(file);
	return true;
}

static size_t DownloadCallBack(void *contents,size_t size,size_t nmemb,FILE *stream){
	size_t written = fwrite(contents,size,nmemb,stream);
	return written;
}
